import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { EntrySynchronizationMethod, intl } from '@/utils';
import { useModel } from 'umi';
import { DevToolBar } from '~/public/cpas-ui';
import { getAccountInfo } from "./service";
import { Item } from 'devextreme-react/toolbar';
import { Button, SelectBox } from "devextreme-react";
import { ZBAdjust } from "./service";
import notify from "devextreme/ui/notify";
import "./index.less";
// import PubSub from 'pubsub-js';


import { ToolBarDataContext } from '../index';

const XMType = window.sessionStorage.electronParams
    ? JSON.parse(window.sessionStorage.electronParams)?.params?.XMType
    : "单机审计项目";


const AdjustToolBar = (props: any) => {
    // debugger;
    const { toolBarData, setToolBarData } = useContext<any>(ToolBarDataContext);

    const { initialState } = useModel('@@initialState');
    const { setAccountInfo } = useModel('useAdjustModel');
    const { whereFrom } = props;
    const { dbname, zcbfid, sjnd } = initialState?.curPart as API.CurPart;
    const { username, usercode } = initialState?.curUser as API.CurUser;
    const userInfoStr = window.localStorage.cpasUserInfo;
    const userInfo = JSON.parse(userInfoStr);
    const password = window.main.cryptoUtil(userInfo.aesPassword);
    const [loadingTimerId, setLoadingTimer] = useState<any>(null);

    const { io } = require('socket.io-client');
    const [accountYearData, setAccountYearData] = useState<any[]>([]);
    const [rollBackBtn, setRollBackBtn] = useState<boolean>(false);

    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", };
    const Titlestyle: React.CSSProperties = { marginRight: "8px" };

    const changeToolBarData = (changeData: any) => {
        setToolBarData((oldData: any) => {
            const newData = { ...oldData, ...changeData };
            return newData;
        });
    }




    const fetchData = async () => {
        const auditAdjustId: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.accountAdjustId ?? sjnd;
        let findTemp = -2;
        const res: any = await getAccountInfo({ dbname });
        if (res.success) {
            findTemp = res.data.findIndex((item: any) => {
                return tempYear === item.Data_ID
            });
            const tempIndex = findTemp >= 0 ? findTemp : 0;
            const DataId = res.data[tempIndex]?.Data_ID;
            const tempDisplayName = res.data[tempIndex]?.displayName;
            res.data.forEach((item: any, index: any) => {
                item.index = index
                return item
            });
            setAccountInfo(res.data);
            setAccountYearData(res.data);
            changeToolBarData({ Data_ID: DataId, showYearName: tempDisplayName, TZQJ: "1", TZQJName: '期末', timesData: `${new Date().getTime()}` });
        }
    };


    useEffect(() => {
        fetchData();
    }, [])

    useEffect(() => {
        const cpasApiUrl = localStorage.getItem("cpasApiUrl");
        const apiUrl = cpasApiUrl && cpasApiUrl.includes("cpasApi") ? cpasApiUrl.replace("/cpasApi", "") : cpasApiUrl;
        const socket = io(apiUrl, {
            connectionStateRecovery: {
                // the backup duration of the sessions and the packets
                maxDisconnectionDuration: 2 * 60 * 1000,
                // whether to skip middlewares upon successful recovery
                skipMiddlewares: true,
            },
            auth: {
                name: "notes"
            }
        });
        socket.on('connect', () => {
            const engine = socket.io.engine;
            console.log('socket connect: ', engine.transport.name); // in most cases, prints "polling"
            engine.on("close", (reason: any) => {
                // called when the underlying connection is closed
                console.log('@@@ socket close: ', reason);
            });
        });

        // either by directly modifying the `auth` attribute
        socket.on("connect_error", () => {
            console.log("@@@ connect_error 连接错误");
        });

        socket.io.on("reconnect_attempt", () => {
            console.log("@@@ reconnect_attempt 尝试重新连接");
        });

        socket.io.on("reconnect", () => {
            console.log("@@@ reconnect 尝试重新连接");
        });

        socket.on("disconnect", (reason: any) => {
            // ...
            console.log("@@@ disconnect 断开连接", reason);
        });

        socket.onAny((eventName: any, ...args: any) => {
            console.log(`@@@ on refresh onAny: ${eventName}`, args);
        });
        socket.on('notesSyncState', (msg: any) => {
            const res = msg ? JSON.parse(msg) : {};
            const tempArgs = res?.args || {};
            console.log('@@@ on refresh ui event: ', res, tempArgs);
            // setIsShowGlobalLoad(false);
            if (res) {
                if (res.ok && tempArgs?.tag === "TZFL2") {
                    clearInterval(loadingTimerId);
                    console.log('@@@ finish');
                    changeToolBarData({ timesData: `${new Date().getTime()}` });
                    notify('同步数据成功！', 'success', 2000);
                } else {
                    notify('同步数据失败！', 'error', 2000);
                }
            }
        });

        return () => {
            // 组件销毁时移除监听事件
            clearInterval(loadingTimerId);
            socket.close();
        }
    }, [loadingTimerId]);


    const onSelectionChangeds = (e: any) => {
        const v: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
        let selectDefaultIDs = JSON.parse(v);
        selectDefaultIDs = { ...selectDefaultIDs, accountAdjustId: e.selectedItem.Data_ID };
        // 本地存储 持久化数据
        window.localStorage.setItem(`selectDefaultTool_${dbname}`, JSON.stringify(selectDefaultIDs))
        changeToolBarData({ Data_ID: e.selectedItem.Data_ID, showYearName: e.selectedItem.displayName, timesData: `${new Date().getTime()}` });
    };

    const onSelectionTZQJ = (e: any) => {
        changeToolBarData({ TZQJ: e.selectedItem.id, TZQJName: e.selectedItem.name, timesData: `${new Date().getTime()}` });
    }

    const onSelectionisTZ = (e: any) => {
        changeToolBarData({ isTZ: e.selectedItem.id, timesData: `${new Date().getTime()}` });
    }
    // const onSelectionisLX = (e: any) => {
    //     setToolBarData({ TZLX: e.selectedItem.id, timesData: `${new Date().getTime()}` });
    // }

    return (
        <>
            <DevToolBar.Default className='ItemStyle'  >
                <Item location="before" >
                    <div style={Divstyle}>
                        <div style={Titlestyle}>
                            {intl('report.subject.account', '账套:')}
                        </div>
                        <div>
                            <SelectBox
                                width={200}
                                items={accountYearData}
                                displayExpr="displayName"
                                valueExpr="displayName"
                                value={toolBarData.showYearName}
                                onSelectionChanged={onSelectionChangeds}
                                dropDownOptions={
                                    { width: '400px' }
                                }
                            />
                        </div>
                    </div>

                </Item>
                <Item location="before" >
                    <div style={Divstyle}>
                        <div style={Titlestyle}>{intl('report.subject.account', '期间:')}</div>
                        <SelectBox
                            width={80}
                            value={toolBarData.TZQJName}
                            items={[
                                {
                                    id: '0',
                                    name: '期初',
                                },
                                {
                                    id: '1',
                                    name: '期末',
                                }
                            ]}
                            displayExpr='name'
                            valueExpr='name'
                            onSelectionChanged={onSelectionTZQJ}
                        />
                    </div>
                </Item>
                <Item location="before" >
                    <div style={Divstyle}>
                        <div style={Titlestyle}>{intl('report.subject.account', '调整状态:')}</div>
                        <SelectBox
                            width={100}
                            items={[
                                {
                                    id: '-1',
                                    name: '全部',
                                },
                                {
                                    id: '0',
                                    name: '未更正',
                                },
                                {
                                    id: '1',
                                    name: '已更正',
                                }
                            ]}
                            displayExpr='name'
                            valueExpr='name'
                            defaultValue='全部'
                            onSelectionChanged={onSelectionisTZ}
                        />
                    </div>
                </Item>
                <Item location="after" >
                    <Button type='default' text='重算调整数' disabled={rollBackBtn} onClick={async () => {
                        setRollBackBtn(true);
                        const r = await ZBAdjust(whereFrom, {
                            dbname,
                            Data_ID: toolBarData.Data_ID,
                            editUser: username,

                        });
                        if (r) notify('重算成功！', 'success', 2000);
                        setRollBackBtn(false);
                    }} />
                    <Button visible={XMType === '单机审计项目' ? false : true} type='default' text='同步' className="withButtonStyle" onClick={() => {
                        const BusID = "调整分录";
                        // setIsShowGlobalLoad(true);
                        EntrySynchronizationMethod({
                            usercode, password, zcbfid, BusID, tag: 'TZFL2'
                        });


                        clearTimeout(loadingTimerId);
                        const timer = setTimeout(() => {
                            notify("未收到同步结果", "error")
                            // setIsShowGlobalLoad(false);
                        }, 120000);
                        setLoadingTimer(timer);
                    }} />
                </Item>
            </DevToolBar.Default>
        </>
    )
};

export default AdjustToolBar;